package org.eclipse.wtp.sample.flashcards;

import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
import java.io.PrintWriter;

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.BufferedWriter;

import javax.servlet.ServletContext;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;

public class NewDictionaryServlet extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// make sure we can get special characters
		if (request.getCharacterEncoding() == null)
			request.setCharacterEncoding("UTF-8");

		// read data from form
		String setName = request.getParameter("newname");
		String key1 = request.getParameter("key1");
		String key2 = request.getParameter("key2");

		// reset message
		request.getSession().setAttribute("message", "");
					
		// catch empty fields
		if (setName.equals("") || key1.equals("") || key2.equals("")) {
			request.getSession().setAttribute("message", "All fields must be filled in.");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/newdictionary.jsp");
			dispatcher.forward(request,response);
			return;
		}
				
		// determine if dictionary name is already used
		response.setContentType("text/html");
		String filename = "/data/dictionaries.txt";
		ServletContext context = getServletContext();
		InputStream inp = context.getResourceAsStream(filename);
		if (inp != null) {
			InputStreamReader isr = new InputStreamReader(inp);
			BufferedReader reader = new BufferedReader(isr);
			String title = "";
			// check each entry
			while ((title = reader.readLine()) != null) {
				if (title.equals(setName)) {
					// set error message and redirect to new dictionary page
					reader.close();
					request.getSession().setAttribute("message", "Dictionary" + setName + "already exists.");
					RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/newdictionary.jsp");
					dispatcher.forward(request,response);
					return;
				}
			}
			reader.close();
		}	
					
		// Create Dictionary
		FlashCardSet flashcardset = new FlashCardSet(setName, key1, key2);
		
		// write dictionary name to names file
		response.setContentType("text/html");
		filename = "/data/dictionaries.txt";
		context = getServletContext();
		String path = context.getRealPath(filename);
		FileWriter fstream = new FileWriter(path, true);
		BufferedWriter out = new BufferedWriter(fstream);
		//out.write("Spanish-English" + "\n");
		//out.write("French-English" + "\n");
		out.write(setName + "\n");
		out.close();
		
		// add new dictionary name to list registered with Session
		ArrayList<String> dictionarylist = (ArrayList<String>)request.getSession().getAttribute("dictionarylist");
		dictionarylist.add(setName);
			
		// create dictionary file
		response.setContentType("text/html");
		filename = flashcardset.getFilename();
		context = getServletContext();
		path = context.getRealPath("/data/");
		System.out.println("new path:" + path);
		System.out.println("making file:" + path + "/" + filename);
		fstream = new FileWriter(path + "/" + filename);
		out = new BufferedWriter(fstream);
		flashcardset.save(out);
		out.close();
					
		// register new dictionary with session
		request.getSession().setAttribute("DD" + flashcardset.getTitle(), flashcardset);
		//request.getSession().setAttribute("loadedsetname", flashcardset.getTitle());
		request.getSession().setAttribute("flashcardset", flashcardset);

		request.getSession().setAttribute("message", "dictionary \"" + setName + "\" successfully created.");

		// redirect to new dictionary page
		getServletContext().getRequestDispatcher("/newdictionary.jsp").forward(request, response);
	}
}